from PySide6.QtWidgets import QWidget,QAbstractItemView,QMenu,QTableWidgetItem,QMessageBox
from PySide6.QtCore import Qt
from sqlalchemy.orm import Session

from views.schoolInfo.schoolinfo import Ui_schoolInfo
from views.schoolInfo.model.SchoolInfo import SchoolInfo
from views.schoolInfo.operationschoolinfoview import OperationSchoolInfo
from settings.publicvar import engine
from settings.publicFuncation.exceldownloadimport import OperationModel


class SchoolInfoView(QWidget, Ui_schoolInfo):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.schoolinfotable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.schoolinfotable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.schoolinfotable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.schoolinfotable.customContextMenuRequested.connect(self.generate_menu)

        self.addschoolinfo.clicked.connect(self.addFun)
        self.importschoolinfo.clicked.connect(self.downloadmodleFun)
        self.exportschoolinfo.clicked.connect(self.importdataFun)
        self.researchschoolinfo.clicked.connect(self.serearchFun)
        self.editschoolinfo.editingFinished.connect(self.serearchFun)
        self.loadTableData()


    # 表格结构
    def setTableStructure(self, data):
        self.schoolinfotable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.schoolinfotable.setItem(i, 0, idx)
            name = QTableWidgetItem(item.name)
            self.schoolinfotable.setItem(i, 1, name)
            schoolnum = QTableWidgetItem(item.schoolnum)
            self.schoolinfotable.setItem(i, 2, schoolnum)
            introduction = QTableWidgetItem(item.introduction)
            self.schoolinfotable.setItem(i, 3, introduction)
            address = QTableWidgetItem(item.address)
            self.schoolinfotable.setItem(i, 4, address)
            mark = QTableWidgetItem(item.mark)
            self.schoolinfotable.setItem(i,5,mark)

    # 加载数据
    def loadTableData(self):
        with Session(engine) as session,session.begin():
            data = session.query(SchoolInfo).all()
            self.setTableStructure(data)

    # 添加数据
    def addFun(self):
        adddialog = OperationSchoolInfo('add',False)
        adddialog.exec()
        self.loadTableData()

    # 获取表单
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deleteitm = menu.addAction('删除')
        action = menu.exec(self.schoolinfotable.mapToGlobal(pos))
        posrow = self.schoolinfotable.currentRow()
        columns = self.schoolinfotable.columnCount()
        data = []
        for i in range(columns):
            item = self.schoolinfotable.item(posrow,i)
            if item is None:
                data.append('')
            else:
                data.append(item.text())

        if action == viewitem:
            view = OperationSchoolInfo('view', data)
            view.exec()
        elif action == changeitem:
            change = OperationSchoolInfo('change', data)
            change.exec()
        elif action == deleteitm:
            delete = OperationSchoolInfo('delete',data)
            delete.exec()
        self.loadTableData()

    # 下载模板
    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('学校信息模板.xlsx')

    # 数据导入
    def importdataFun(self):
        names = ['idx','name','schoolnum','introduction','address','mark']
        dtypes = {'schoolnum':str}
        data = OperationModel().importdataFun(names,dtypes)
        with Session(engine) as session, session.begin():
            exist_schoolinfo = session.query(SchoolInfo).filter(
                SchoolInfo.schoolnum.in_(data.schoolnum.to_list())).all()

            if exist_schoolinfo:
                save_schools = data.to_dict('records')
            else:
                exist_schoolinfo_schoolnum = [tem.schoolnum for tem in exist_schoolinfo]
                save_schools = data[~data.schoolnum.isin(exist_schoolinfo_schoolnum)].to_dict('records')
            schoolinfos = [SchoolInfo(**item) for item in save_schools]
            session.add_all(schoolinfos)
            QMessageBox.information(None,'成功','成功%s条，失败%s条'%(len(schoolinfos),(len(data)-len(schoolinfos))))
            self.loadTableData()

    # 搜索
    def serearchFun(self):
        researchData = self.editschoolinfo.text().strip()
        if researchData == "":
            QMessageBox.critical(None,'失败','你没有输入数据!')
            self.loadTableData()
        else:
            with Session(engine) as session,session.begin():
                sereachName = session.query(SchoolInfo).filter(
                    SchoolInfo.name.like('%' + researchData + '%')).all()
                sereachNum = session.query(SchoolInfo).filter(
                    SchoolInfo.schoolnum.like('%' + researchData + '%')).all()

                result_data = sereachName + sereachNum
                if result_data:
                    self.setTableStructure(result_data)
                else:
                    QMessageBox.critical(None,'没有数据','你搜索数据不存在！')